<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 车辆里程记录模型
 * @package app\model\oa
 */
class CarMileage extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'car_mileage';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'car_id' => 'integer',
        'mileage' => 'float',
        'admin_id' => 'integer',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    /**
     * 关联车辆
     */
    public function car()
    {
        return $this->belongsTo('app\model\oa\Car', 'car_id', 'id');
    }

    /**
     * 关联管理员
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User', 'admin_id', 'id');
    }

    /**
     * 获取最新里程数
     */
    public static function getLatestMileage($carId)
    {
        return self::where('car_id', $carId)
            ->order('create_time', 'desc')
            ->value('mileage');
    }

    /**
     * 获取里程记录列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['car', 'admin'])
            ->order('create_time', 'desc');

        // 按车辆筛选
        if (!empty($params['car_id'])) {
            $query->where('car_id', $params['car_id']);
        }

        return $query->paginate($params['limit'] ?? 15);
    }
}